<?php

class TextToHtml {

	public static function GetHtml($entry_text, $noFollowLinks, $truncateLinkAt) {
		$inputstr = $entry_text;
		$inputstr = htmlentities($inputstr);
		
		$outputstr = "";
		$outputstr .= trim($inputstr);

		// Pad out spaces.
		$outputstr = str_replace("  ", "&nbsp; ", $outputstr);
		// Add line break markup.
		$outputstr = TextToHtml::insertLineBreakMarkup($outputstr);
		// Add link markup.
		$outputstr = TextToHtml::insertAnchorMarkup($outputstr, $noFollowLinks, $truncateLinkAt);
		return $outputstr;
	}

	private static function insertLineBreakMarkup($str) {
		return str_replace("\r\n", "\r\n" . "<br/>", $str);
	}

	private static function insertAnchorMarkup($content, $noFollowLinks, $truncateLinkAt) {
		$cursor = 0;
		$contentParsed = "";

		while (strpos($content, "http://", $cursor) !== false) {
			//echo " link! ";
			$aStart = strpos($content, "http://", $cursor); // mark the beginning of the next link.
			$aEnd = strlen($content); // mark the longest the link could possibly be.

			//shorten link length if we find any special "end link" characters before the end.
			$aEndTest = strpos($content, " ", $aStart);
			if ($aEndTest > 0 && $aEndTest < $aEnd) $aEnd = $aEndTest;
			$aEndTest = strpos($content, ". ", $aStart);
			if ($aEndTest > 0 && $aEndTest < $aEnd) $aEnd = $aEndTest;
			$aEndTest = strpos($content, ".)", $aStart);
			if ($aEndTest > 0 && $aEndTest < $aEnd) $aEnd = $aEndTest;
			$aEndTest = strpos($content, ")", $aStart);
			if ($aEndTest > 0 && $aEndTest < $aEnd) $aEnd = $aEndTest;

			//if (strpos($content, '"', $aStart) === false)
			//	echo"@";
			$aEndTest = strpos($content, '"', $aStart);  // for some reason, not working!
			if ($aEndTest > 0 && $aEndTest < $aEnd) $aEnd = $aEndTest;
			
			$aEndTest = strpos($content, "'", $aStart);
			if ($aEndTest > 0 && $aEndTest < $aEnd) $aEnd = $aEndTest;
			$aEndTest = strpos($content, "\r\n", $aStart);
			if ($aEndTest > 0 && $aEndTest < $aEnd) $aEnd = $aEndTest;
			
			$contentParsed .= substr($content, $cursor, $aStart - $cursor);
			$contentParsed .= '<a' . ($noFollowLinks ? " rel='nofollow'" : "") . ' href="' . substr($content, $aStart, $aEnd - $aStart) . '">';
			if ($truncateLinkAt == false) {
				$contentParsed .= substr($content, $aStart, $aEnd - $aStart);
			}
			else {
				$contentParsed .= TextToHtml::truncate(substr($content, $aStart, $aEnd - $aStart), $truncateLinkAt);
			}
			$contentParsed .= "</a>";
			$cursor = $aEnd;
		}
		// add the rest of the content string.
		$contentParsed = $contentParsed . substr($content, $cursor);
		return $contentParsed;
	}

	private static function truncate($inputstr, $truncateAt) {
		if (strlen($inputstr) > $truncateAt) {
			return substr($inputstr, 0, $truncateAt - 2) . "...";
		} else {
			return $inputstr;
		}
	}

}

?>